/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.third.daikai.mabang.service;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.ImageCompressUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.third.aliyunocr.utils.HttpUtils;
import org.jeecg.modules.third.daikai.mabang.dto.MbDriverDTO;
import org.jeecg.modules.third.daikai.mabang.dto.MbVehicleDTO;
import org.jeecg.modules.third.daikai.mabang.dto.MbWaybillDTO;
import org.jeecg.modules.third.dongjiang.tax.system.utils.HttpUtil;
import org.jeecg.modules.third.daikai.mabang.constant.MaBangConstant;
import org.jeecg.modules.wlhy.utils.HyCfgUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsPackage: org.jeecg.modules.third.mabang
 * @Author: duanlikao
 * @CreateTime: 2022-08-16 10:14
 * @Description: 马帮代开
 * @Version: 1.0
 */
@Service
public class MaBangApiService {

    @Autowired
    private RedisUtil redisUtil;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    //银行文件路径
    @Value(value = "${jeecg.path.bank}")
    private String bankPath;


    private static final Logger LOGGER = LoggerFactory.getLogger(MaBangApiService.class);


    /**
     * 获取系统Token
     * @return
     */
    private String getToken(){
        if(!HyCfgUtil.isUsed("mabang_daikai")){
            throw new JeecgBootException("马帮服务暂未开启,请联系管理。");
        }

        Object tokenObject  =
                redisUtil.hasKey(MaBangConstant.MABANG_API_TOKEN_KEY) ?
                        redisUtil.get(MaBangConstant.MABANG_API_TOKEN_KEY) : null;
        if(tokenObject != null){
            return tokenObject.toString();
        }
        try {
            String url = HyCfgUtil.getCfgItem("mabang_daikai","mb_url") + "rest/login/authenticate";
            Map<String, String> map = new HashMap<>();
            map.put("userName",HyCfgUtil.getCfgItem("mabang_daikai","mb_userName"));
            map.put("password",HyCfgUtil.getCfgItem("mabang_daikai","mb_password"));

            String jsonString = JSONObject.toJSONString(map);
            String res = HttpUtil.doNewPost(url, jsonString);
            LOGGER.info("MaBangApiService getToken url | {} jsonString | {} result | {}" ,url, jsonString ,res);
            if(StringUtils.isEmpty(res)){
                throw new JeecgBootException("MaBangApiService getToken 失败");
            }
            Result r = JSONObject.parseObject(res,Result.class);

            if (r.isSuccess() && 200 == r.getCode()) {
                if(StringUtils.isNotBlank(r.getResult().toString())){
                    redisUtil.set(MaBangConstant.MABANG_API_TOKEN_KEY, r.getResult().toString(), MaBangConstant.MABANG_API_TOKEN_KEY_EXPIRE);
                    return r.getResult().toString();
                }else {
                    throw new JeecgBootException("MaBangApiService getToken 获取token失败" );
                }
            }else{
                throw new JeecgBootException(r.getMessage());
            }
        } catch (Exception e) {
            LOGGER.info("MaBangApiService getToken Exception | {}" ,e.getMessage());
            throw new JeecgBootException(e.getMessage() );
        }

    }

    //业务接口认证公共头部
    private Map<String, String> getHeaders(String token){
        Map<String, String> headers = new HashMap<>();
        headers.put("X-Access-Token",  token);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        headers.put("User-Agent", "Mozilla/4.76");
        return headers;
    }


    /**
     * 图片上传
     * @param imgUrl
     * @return
     */
    public  String uploadFiles(String imgUrl, String type) {

        if(StringUtils.isEmpty(imgUrl)){
            LOGGER.info("MaBangApiService uploadFiles isEmpty:{}", imgUrl);
            return StringUtils.EMPTY;
        }
        if(!HyCfgUtil.isUsed("mabang_daikai")){
            throw new JeecgBootException("马帮服务暂未开启,请联系管理。");
        }

        String pathTmp = "";
        if (!"银行回单".equals(type)) {
            pathTmp =  uploadpath  + File.separator +imgUrl;
            //文件名是pdf改成jpg
            String suffix = imgUrl.substring(imgUrl.lastIndexOf("."));
            if(suffix.equals(".pdf")){
                pathTmp =  uploadpath  + File.separator + imgUrl.substring(0, imgUrl.lastIndexOf(".")) + ".jpg";
                File file = new File(pathTmp);
                if (!file.exists()) {
                    pathTmp =  bankPath  + File.separator +  imgUrl.substring(0, imgUrl.lastIndexOf(".")) + ".jpg";
                }
            }
            File file = new File(pathTmp);
            if (!file.exists()) {
                LOGGER.info("MaBangApiService uploadFiles exists:{}" ,pathTmp);
                throw new JeecgBootException("上传的图片不存在!");
            }
        } else {
            pathTmp = imgUrl;
        }

        try{

            String token = getToken();
            //判断token空
            if(StringUtils.isEmpty(token)) {
                throw new JeecgBootException("马帮服务Token为空！");
            }

            Map<String, String> headers = getHeaders(token);
            Map<String, String> querys = new HashMap<>();
            String urlPath =  "sys/common/whly/uploadImgBase64";
            Map <String, String> map = new HashMap <>();
            map.put("imageBase64", ImageCompressUtil.imageToBase64(pathTmp));

            String bodys = JSONObject.toJSONString(map);
            LOGGER.info("MaBangApiService uploadFiles url :{} bodys :{}", urlPath , pathTmp);
            HttpResponse response = HttpUtils.doPost(HyCfgUtil.getCfgItem("mabang_daikai","mb_url") ,  urlPath, "POST", headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if (stat == 200){
                String res = EntityUtils.toString(response.getEntity() ,"UTF-8");
                LOGGER.info("MaBangApiService uploadFiles res_obj :{} ",res);
                Result r = JSONObject.parseObject(res,Result.class);

                if (r.isSuccess() && 0 == r.getCode()) {
                    if(StringUtils.isNotBlank(r.getMessage())){
                        return r.getMessage();
                    }else {
                        throw new JeecgBootException("MaBangApiService uploadFiles 上传图片失败" );
                    }
                }else{
                    throw new JeecgBootException(r.getMessage());
                }

            }else{
                LOGGER.info("MaBangApiService uploadFiles Http code: {}  | http header error msg: {} | Http body error msg: {}",
                        stat, response.getFirstHeader("X-Ca-Error-Message"), EntityUtils.toString(response.getEntity()));
                throw new JeecgBootException("HTTP请求失败！" + stat);
            }

        }catch (Exception e){
            LOGGER.info("MaBangApiService uploadFiles Exception:{}",e.getMessage());
        }
        return StringUtils.EMPTY;
    }


    public String driverPush(MbDriverDTO driver){
        if(!HyCfgUtil.isUsed("mabang_daikai")){
            throw new JeecgBootException("马帮服务暂未开启,请联系管理。");
        }
        if(driver == null){
            throw new JeecgBootException("提交数据不能为空！");
        }

        String token = getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("马帮服务Token为空！");
        }

        Map<String, String> headers = getHeaders(token);
        Map<String, String> querys = new HashMap<>();
        String bodys = JSONObject.toJSONString(driver);
        String path = "hydriver/hyDriver/transmission";
        LOGGER.info("driverPush url :{} bodys :{}", HyCfgUtil.getCfgItem("mabang_daikai","mb_url")+ path , bodys);
        try {
            HttpResponse response = HttpUtils.doPost(HyCfgUtil.getCfgItem("mabang_daikai","mb_url") ,  path, "POST", headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if (stat == 200){
                String res = EntityUtils.toString(response.getEntity(),"UTF-8");
                LOGGER.info("driverPush res_obj :{} ",res);
                return res;
            }else{
                LOGGER.info("driverPush Http code: {}  | http header error msg: {} | Http body error msg: {}",
                        stat, response.getFirstHeader("X-Ca-Error-Message"), EntityUtils.toString(response.getEntity()));
                throw new JeecgBootException("HTTP请求失败！" + stat);
            }
        } catch (Exception e) {
            LOGGER.info("driverPush Exception :{} ",e.getMessage());
            throw new JeecgBootException("操作失败！" + e.getMessage());
        }

    }

    public String vehiclePush(MbVehicleDTO vehicle){
        if(!HyCfgUtil.isUsed("mabang_daikai")){
            throw new JeecgBootException("马帮服务暂未开启,请联系管理。");
        }
        if(vehicle == null){
            throw new JeecgBootException("提交数据不能为空！");
        }

        String token = getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("马帮服务Token为空！");
        }

        Map<String, String> headers = getHeaders(token);
        Map<String, String> querys = new HashMap<>();
        String bodys = JSONObject.toJSONString(vehicle);
        String path = "hyVehicle/hyVehicle/transmission";
        LOGGER.info("vehiclePush url :{} bodys :{}", HyCfgUtil.getCfgItem("mabang_daikai","mb_url")+ path , bodys);
        try {
            HttpResponse response = HttpUtils.doPost(HyCfgUtil.getCfgItem("mabang_daikai","mb_url") ,  path, "POST", headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if (stat == 200){
                String res = EntityUtils.toString(response.getEntity(),"UTF-8");
                LOGGER.info("vehiclePush res_obj :{} ",res);
                return res;
            }else{
                LOGGER.info("vehiclePush Http code: {}  | http header error msg: {} | Http body error msg: {}",
                        stat, response.getFirstHeader("X-Ca-Error-Message"), EntityUtils.toString(response.getEntity()));
                throw new JeecgBootException("HTTP请求失败！" + stat);
            }
        } catch (Exception e) {
            LOGGER.info("vehiclePush Exception :{} ",e.getMessage());
            throw new JeecgBootException("操作失败！" + e.getMessage());
        }

    }



    /**
     *
     * @param paramDTO
     * @return
     */
    public String waybillPush(MbWaybillDTO paramDTO){
        if(!HyCfgUtil.isUsed("mabang_daikai")){
            throw new JeecgBootException("马帮服务暂未开启,请联系管理。");
        }
        if(paramDTO == null){
            throw new JeecgBootException("提交数据不能为空！");
        }

        String token = getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("马帮服务Token为空！");
        }

        Map<String, String> headers = getHeaders(token);
        Map<String, String> querys = new HashMap<>();
        String bodys = JSONObject.toJSONString(  Collections.singletonList( paramDTO) );
        String path = "shipping/hyShippingNote/transmission";
        LOGGER.info("waybillPush url :{} bodys :{}", HyCfgUtil.getCfgItem("mabang_daikai","mb_url")+ path , bodys);
        try {
            HttpResponse response = HttpUtils.doPost(HyCfgUtil.getCfgItem("mabang_daikai","mb_url") ,  path, "POST", headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if (stat == 200){
                String res = EntityUtils.toString(response.getEntity(),"UTF-8");
                LOGGER.info("waybillPush res_obj :{} ",res);
                  return res;
            }else{
                LOGGER.info("waybillPush Http code: {}  | http header error msg: {} | Http body error msg: {}",
                        stat, response.getFirstHeader("X-Ca-Error-Message"), EntityUtils.toString(response.getEntity()));
                throw new JeecgBootException("HTTP请求失败！" + stat);
            }
        } catch (Exception e) {
            LOGGER.info("waybillPush Exception :{} ",e.getMessage());
            throw new JeecgBootException("操作失败！" + e.getMessage());
        }

    }

}
